package com.topfinance.cnaps2.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;

import com.topfinance.cnaps2.dto.SysUserDto;
import com.topfinance.cnaps2.ebo.SysOrgEbo;
import com.topfinance.cnaps2.ebo.SysUserEbo;
import com.topfinance.cnaps2.service.ISysUserManager;
import com.topfinance.frame.dao.HibernateEntityDao;
import com.topfinance.frame.exception.AppException;

/**
 * 该类自动实现了dao的一般方法，如add, remove, update
 * 在service中出现的大部分情况下是在向后台提交数据前的处理(如校验)及获取后台数据后的处理等
 * @author
 *
 */

public class SysUserManagerImpl extends HibernateEntityDao<SysUserEbo> implements ISysUserManager {

	private static final Log log = LogFactory.getLog(SysUserManagerImpl.class);

	public void addUser(SysUserDto ut) throws AppException{
		SysOrgEbo oo = (SysOrgEbo)get(SysOrgEbo.class,ut.getOID());
		SysUserEbo u = new SysUserEbo();
		BeanUtils.copyProperties(ut, u);
		u.setCreateDate(new Date());
		u.setORG(oo);	
    	save(u);
    }
	
	public void editUser(SysUserDto ut) throws AppException{
		SysOrgEbo oo = (SysOrgEbo)get(SysOrgEbo.class,ut.getOID());
		//load the date previously
		SysUserEbo u = (SysUserEbo)get(ut.getID());
		Date cdate = u.getCreateDate();
		BeanUtils.copyProperties(ut, u);
		u.setORG(oo);
		//权宜之计，先用着
		u.setCreateDate(cdate);
    	update(u);
    }
	
	//获得用户
	public SysUserEbo getUser(Integer id) throws AppException{
		return (SysUserEbo)get(id);
	}

	public void deleteUser(SysUserEbo o) throws AppException{
		removeById(o.getClass(),o.getID());
    }
	public void deleteUser(Integer id) throws AppException{
		removeById(SysUserEbo.class,id);
	}

	//获得用户列表
	public List getAllUserList(String oid) throws AppException{
		String hql = " select new com.topfinance.cnaps2.dto.SysUserExDto";
		//Integer id, Integer oid, String name, String loginname, String password, String phone, String cell, String email, String desc
		hql += "(t.ID,t.ORG.OID,t.name,t.loginname,t.password,t.phone,t.cell,t.email,t.desc) from SysUserEbo t " ;
		if(oid != null && oid.length() > 0)
			hql += " where t.ORG.OID = " + oid;
		//String where = "";
		//List<Object> paramList = new ArrayList<Object>();
//		if (isNotBlank(where)) {
//			where = " where " + where;
//		}
//		hql = hql + where;
		return find(hql);
	}
	
	public SysUserEbo checkLoginUser(String loginname, String password) throws AppException{
		String hql = " from SysUserEbo t ";
		hql += " where t.loginname = '" + loginname+ "'";
		hql += " and t.password = '" + password + "'";
		List list = find(hql);
		if(list.size()==1)
			return (SysUserEbo)list.get(0);
		else
			return null;
	}
}
